package hephaestus.server.proxy;

import java.util.*;
import java.net.*;

public class IncomingManager {
	private List<IncomingConnection> incoming;
	private List<IncomingConnection> waiting;
	private ConnectionManager connections;
	private String internalAddressPrefix;
	private int maximumQueued;
	
	public IncomingManager(ConnectionManager connections, String internalAddressPrefix, int maxQueued)
	{
		incoming = new ArrayList<IncomingConnection>(maxQueued);
		waiting = new ArrayList<IncomingConnection>(maxQueued);
		this.internalAddressPrefix = internalAddressPrefix;
		this.connections = connections;
		maximumQueued = maxQueued;
	}
	
	private void startConnection(IncomingConnection connection)
	{
		incoming.add(connection);
		connection.start();
	}
	
	public void incomingConnection(Socket client)
	{
		IncomingConnection connection = new IncomingConnection(connections, this, internalAddressPrefix, client);
		if(incoming.size() < maximumQueued)
		{
			startConnection(connection);
		}
		else
		{
			waiting.add(connection);
		}
	}
	
	public void dequeueIncomingConnection(IncomingConnection queued)
	{
		incoming.remove(queued);
		if(!waiting.isEmpty())
		{
			IncomingConnection connection = waiting.get(0);
			waiting.remove(connection);
			startConnection(connection);
		}
	}
}
